var express = require('express')
var path = require('path')
var mongoose = require('mongoose')
var bodyParser = require('body-parser')
var Cookies = require('cookies');
var User = require('./models/User')

var app = express()

// 配置静态文件
app.use('/public/', express.static(path.join(__dirname, './public/')))
app.use('./node_modules/', express.static(path.join(__dirname, './node_modules/')))

// 配置模板引擎
app.engine('html', require('express-art-template'))
// 配置模板引擎默认目录
app.set('views', path.join(__dirname, './views/'))

// 配置body-parser
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 配置中间件  cookie
app.use(function(req, res, next){
  // 获取登陆的cookie信息
  console.log(111)
  req.cookies = new Cookies(req, res)
  // 保存cookie中的用户信息
  req.userInfo = {}
  if(req.cookies.get('userInfo')) {
    try {
      req.userInfo = JSON.parse(req.cookies.get('userInfo'))

      // 判断是不是管理员
      User.findById(req.userInfo._id).then(function(userInfo) {
        console.log('判断是不是管理员')
        req.userInfo.isAdmin = Boolean(userInfo.isAdmin)
        next()
      })
    } catch (e) {
      next()
    }
  }else {
    next()
  }
})


// 配置路由
app.use('/', require('./routers/main.js'))
app.use('/api', require('./routers/api'))
// app.use('/admin', require('./routers/admin'))

// 连接数据库
mongoose.connect('mongodb://localhost/blog')

var db = mongoose.connection
db.on('error', console.error.bind(console, '数据库连接失败'))
db.once('open', function () {
  console.log('数据库连接成功')
  app.listen(8000, function () {
    console.log('博客服务器启动完成,端口8000...')
  })
});
